package cn.ltpcloud.common.handler;


import cn.ltpcloud.common.constant.HttpStatus;
import cn.ltpcloud.common.entity.AjaxResult;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

import static cn.ltpcloud.common.utils.JsonUtils.OBJECT_MAPPER;

/**
 * 授权异常处理器
 *
 * @author jiejiebiezheyang
 * @since 2023-04-03 22:46
 */
@Component
public class AccessExceptionHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        // 处理异常,返回错误信息
        AjaxResult err = AjaxResult.error(HttpStatus.FORBIDDEN, "Access Denied");
        String json = OBJECT_MAPPER.writeValueAsString(err);
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().println(json);
    }
}
